package com.zx.dsptuneup_cloud.Common.circleView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.zx.dsptuneup_cloud.R;

/**
 *  圆弧
 */
public class ArcControlViewSmall extends View {
    // 控件宽
    private int width;
    // 控件高
    private int height;

    private int centerX;

    private int centerY;
    // 刻度盘半径
    private int dialRadius;
    // 刻度高
    private int scaleHeight = dp2px(10);
    // 刻度盘画笔
    private Paint mArcPaint;
    // 旋转按钮画笔
    private Paint buttonPaint;
    //圆弧的画笔的宽度
    private int mStrokeWith=5;
    // db
    private int dbInfo = 0;
    // 最低db
    private int minDb = 0;
    // 最高db
    private int maxDb = 7;
    // 1格代表1db
    private int angleRate = 01;
    // 每格的角度
    private float angleOne = (float) (225 / (maxDb - minDb) / angleRate);
    // 按钮图片
    private Bitmap buttonImage = BitmapFactory.decodeResource(getResources(),
            R.mipmap.circle_knob_small);
    // 按钮图片阴影
    private Bitmap buttonImageShadow = BitmapFactory.decodeResource(getResources(),
            R.mipmap.circle_knob_2_small);

    private Bitmap buttonImageDisk = BitmapFactory.decodeResource(getResources(),
            R.mipmap.circle_knob_d_small);
    // 抗锯齿
    private PaintFlagsDrawFilter paintFlagsDrawFilter;
    // 增益改变监听
    private ArcControlViewSmall.OnDbChangeListener onDbChangeListener;
    // 控件点击监听
    private ArcControlViewSmall.OnClickListener onClickListener;
    // 控件滑动监听
    private  ArcControlViewSmall.OnDbMoveListener onDbMoveListener;
    // 以下为旋转按钮相关

    // 当前按钮旋转的角度
    private float rotateAngle;
    // 当前的角度
    private float currentAngle;
    /**
     * 是否可以旋转
     */
    private boolean canRotate = false;

    public ArcControlViewSmall(Context context) {
        this(context, null);
    }

    public ArcControlViewSmall(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ArcControlViewSmall(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //圆弧的paint
        mArcPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        //抗锯齿
        mArcPaint.setAntiAlias(true);
        mArcPaint.setColor(Color.BLACK);
        //设置透明度（数值为0-255）
        mArcPaint.setAlpha(100);
        //设置画笔的画出的形状
        mArcPaint.setStrokeJoin(Paint.Join.ROUND);
        mArcPaint.setStrokeCap(Paint.Cap.ROUND);
        //设置画笔类型
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setStrokeWidth(dp2px(mStrokeWith));

        buttonPaint = new Paint();
        paintFlagsDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 控件宽、高
        width = height = Math.min(h, w) - dp2px(40);
        // 刻度盘半径
        dialRadius = width / 2 + dp2px(10);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawArc(canvas);
        drawButton(canvas);
    }


    /**
     * 绘制刻度盘圆弧
     *Arc
     * @param canvas 画布
     */
    private void drawArc(Canvas canvas) {
        canvas.save();
        canvas.translate(getWidth() / 2, getHeight() / 2);
        // 顺时针旋转112-2度
//        canvas.rotate((float) (112.5 - 2));
        mArcPaint.setColor(Color.BLACK);
        RectF rectF = new RectF(-dialRadius, -dialRadius, dialRadius, dialRadius);
        canvas.drawArc(rectF, (float)157.5, 225, false, mArcPaint);

        //绘制当前数值对应的圆弧
        mArcPaint.setColor(getResources().getColor(R.color.circleYellow));
        canvas.drawArc(rectF,(float)157.5,rotateAngle,false,mArcPaint);
        canvas.restore();
    }

    /**
     * 绘制旋转按钮
     *
     * @param canvas 画布
     */
    private void drawButton(Canvas canvas) {
        // 按钮宽高
        int buttonWidth = buttonImage.getWidth();
        int buttonHeight = buttonImage.getHeight();
        // 按钮阴影宽高
        int buttonShadowWidth = buttonImageShadow.getWidth();
        int buttonShadowHeight = buttonImageShadow.getHeight();
        // 底盘宽高
        int buttonDiskWidth = buttonImageDisk.getWidth();
        int buttonDiskHeight = buttonImageDisk.getHeight();


        // 绘制按钮阴影
        canvas.drawBitmap(buttonImageShadow, (getWidth() - buttonShadowWidth) / 2,
                (getHeight() - buttonShadowHeight) / 2, buttonPaint);

        //  绘制底盘
        canvas.drawBitmap(buttonImageDisk, (getWidth() - buttonDiskWidth) / 2,
                (getHeight() - buttonDiskHeight) / 2, buttonPaint);


        Matrix matrix = new Matrix();
        // 设置按钮位置，移动到控件中心
        matrix.setTranslate((getWidth() - buttonWidth) / 2, (getHeight() - buttonHeight) / 2);
        // 设置旋转角度，旋转中心为控件中心，当前也是按钮中心
        matrix.postRotate((float) (rotateAngle - 112.5), getWidth() / 2, getHeight() / 2);

        //设置抗锯齿
        canvas.setDrawFilter(paintFlagsDrawFilter);
        canvas.drawBitmap(buttonImage, matrix, buttonPaint);
    }


    private boolean isDown;
    private boolean isMove;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!canRotate) {
            return super.onTouchEvent(event);
        } else {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isDown = true;
                    float downX = event.getX();
                    float downY = event.getY();
                    currentAngle = calcAngle(downX, downY);
                    break;

                case MotionEvent.ACTION_MOVE:
                    isMove = true;
                    float targetX;
                    float targetY;
                    downX = targetX = event.getX();
                    downY = targetY = event.getY();
                    float angle = calcAngle(targetX, targetY);

                    // 滑过的角度增量
                    float angleIncreased = angle - currentAngle;

                    // 防止越界
                    if (angleIncreased < -225) {
                        angleIncreased = angleIncreased + 360;
                    } else if (angleIncreased > 225) {
                        angleIncreased = angleIncreased - 360;
                    }

                    IncreaseAngle(angleIncreased);
                    currentAngle = angle;

                    if (onDbMoveListener != null) {
                        onDbMoveListener.moveChange(dbInfo);
                    }

                    invalidate();
                    break;

                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP: {
                    if (isDown) {
                        if (isMove) {
                            // 纠正指针位置
                            rotateAngle = (float) ((dbInfo - minDb) * angleRate * angleOne);
                            invalidate();
                            // 回调增益改变监听
                            if (onDbChangeListener != null) {
                                onDbChangeListener.change(dbInfo);
                            }
                            isMove = false;
                        } else {
                            // 点击事件
                            if (onClickListener != null) {
                                onClickListener.onClick(dbInfo);
                            }
                        }
                        isDown = false;
                    }
                    break;
                }
            }
            return true;
        }
    }

    /**
     * 以按钮圆心为坐标圆点，建立坐标系，求出(targetX, targetY)坐标与x轴的夹角
     *
     * @param targetX x坐标
     * @param targetY y坐标
     * @return (targetX, targetY)坐标与x轴的夹角
     */
    private float calcAngle(float targetX, float targetY) {
        float x = targetX - getWidth() / 2;
        float y = targetY - getHeight() / 2;
        double radian;

        if (x != 0) {
            float tan = Math.abs(y / x);
            if (x > 0) {
                if (y >= 0) {
                    radian = Math.atan(tan);
                } else {
                    radian = 2 * Math.PI - Math.atan(tan);
                }
            } else {
                if (y >= 0) {
                    radian = Math.PI - Math.atan(tan);
                } else {
                    radian = Math.PI + Math.atan(tan);
                }
            }
        } else {
            if (y > 0) {
                radian = Math.PI / 2;
            } else {
                radian = -Math.PI / 2;
            }
        }
        return (float) ((radian * 180) / Math.PI);
    }

    /**
     * 增加旋转角度
     *
     * @param angle 增加的角度
     */
    private void IncreaseAngle(float angle) {
        rotateAngle += angle;
        if (rotateAngle < 0) {
            rotateAngle = 0;
        } else if (rotateAngle > 225) {
            rotateAngle = 225;
        }
        // 加上0.5是为了取整时四舍五入
        dbInfo = (int) ((rotateAngle / angleOne) / angleRate + 0.5) + minDb;
    }

    /**
     * 设置几格代表1db，默认1格
     *
     * @param angleRate 几格代表1db
     */
    public void setAngleRate(int angleRate) {
        this.angleRate = angleRate;
    }

    /**
     * 设置db
     *
     * @param db 设置的db
     */
    public void setDB(int db) {
        setDB(minDb, maxDb, db);
    }


    /**
     * 设置增益
     *
     * @param minDb 最小db
     * @param maxDB 最大db
     * @param db    设置的db
     */
    public void setDB(int minDb, int maxDB, int db) {
        this.minDb = minDb;
        this.maxDb = maxDB;
        if (db < minDb) {
            this.dbInfo = minDb;
        } else {
            this.dbInfo = db;
        }
        // 计算每格的角度
        angleOne =  (225 / (float)(maxDB - minDb) / angleRate);
        // 计算旋转角度
        rotateAngle = (float) ((db - minDb) * angleRate * angleOne);

        invalidate();
    }

    /**
     * 设置旋钮是否可以旋转
     *
     * @param canRotate
     */
    public void setCanRotate(boolean canRotate) {
        this.canRotate = canRotate;
    }

    public boolean getCanRotate() {
        return this.canRotate;
    }


    /**
     * 设置增益改变监听
     *
     * @param onDbChangeListener 监听接口
     */

    public void setOnDbChangeListener(ArcControlViewSmall.OnDbChangeListener onDbChangeListener) {
        this.onDbChangeListener = onDbChangeListener;
    }

    public void setOnDbMoveListener(OnDbMoveListener onDbMoveListener) {
        this.onDbMoveListener = onDbMoveListener;
    }

    /**
     * 设置点击监听
     *
     * @param onClickListener 点击回调接口
     */
    public void setOnClickListener(ArcControlViewSmall.OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    /**
     * db滑动改变监听接口
     */
    public interface OnDbMoveListener {
        /**
         * 回调方法
         *
         * @param db 增益
         */
        void moveChange(int db);
    }

    /**
     * db抬起改变监听接口
     */
    public interface OnDbChangeListener {
        /**
         * 回调方法
         *
         * @param db 增益
         */
        void change(int db);
    }

    /**
     * 点击回调接口
     */
    public interface OnClickListener {
        /**
         * 点击回调方法
         *
         * @param db 增益
         */
        void onClick(int db);
    }

    public int dp2px(float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private int sp2px(float sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
                getResources().getDisplayMetrics());
    }
}
